import requests
from datetime import datetime


class Push:
    token = ""

    def __init__(self):
        self.host = "http://192.168.0.19:8998/"
        self.username = "root"
        self.passwd = "root"
        self.token = ""
        self.timeout = 6

    def login(self):
        url = self.host + "/lotterys/sys/login"
        data = {"username": self.username, "password": self.passwd}

        print("登陆了！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！")

        res = requests.post(url, json=data, timeout=self.timeout)
        if res.status_code == 200:
            self.token = res.text

    def push_data(self, issue, numbers, lottery, lotteryType, openTime):

        # 格式化 openTime 并转为时间戳
        open_time_str = openTime.replace("T", " ")
        dt = datetime.strptime(open_time_str, "%Y-%m-%d %H:%M:%S")
        openTime_timestamp = int(dt.timestamp())

        numbers_list = numbers.split(',')
        qian3 = ','.join(numbers_list[:3])
        zhong3 = ','.join(numbers_list[1:4])
        hou3 = ','.join(numbers_list[-3:])
        self.upload({
            "issue": issue,
            "numbers": qian3,
            "lottery": lottery+'-Q3',
            "lotteryType": lotteryType,
            "openTime": openTime_timestamp
        })
        self.upload({
            "issue": issue,
            "numbers": zhong3,
            "lottery": lottery+'-Z3',
            "lotteryType": lotteryType,
            "openTime": openTime_timestamp
        })
        self.upload({
            "issue": issue,
            "numbers": hou3,
            "lottery": lottery+'-H3',
            "lotteryType": lotteryType,
            "openTime": openTime_timestamp
        })

    def upload(self, data):
        url = self.host + "/lotterys/biz-open-collection/push"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.token}"
        }
        res = requests.post(url, json=data, headers=headers)
        print(data, "推送数据")
        if res.status_code == 401:
            self.login()
            headers["Authorization"] = f"Bearer {self.token}"
            res = requests.post(url, json=data, headers=headers, timeout=self.timeout)
        print(res.status_code, res.text)

